import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.*;

/**
 * @author
 *
 */
public class EntityManager implements ComponentCollection.GameComponent {
	
	ArrayList<Entity> entitys;
	public EntityManager()
	{
		entitys = new ArrayList<Entity>();
 	}
	
	public void addEntity(Entity entity)
	{
		entity.setup(this);
		entitys.add(entity);
	}
	
	public List<Entity> getEntitys()
	{
		return new ArrayList<Entity>(entitys);
	}
	
	public List<Entity> getEntitys(ObstacleFilter...filters)
	{
	
		List<Entity> collection = getEntitys();
		for(int  i = 0; i < collection.size(); i++)
		{
			Entity entity = collection.get(i);
			for(ObstacleFilter filter : filters)
				if(filter.filterObstacle(entity))
				{
					collection.remove(i);
					i--;
				}
		}
		return collection;
	}

	@Override
	public void initialise(ComponentCollection colection) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void render(Graphics2D g) {
		for(Entity ent : entitys)
			ent.draw(g);
	}

	@Override
	public void update(float dt) {
		for(Entity ent : entitys)
			ent.update(dt);
		
	}
	
	interface ObstacleFilter 
	{
		/**
		 * If this filter returns true then it removes it from the collection
		 * @param entity
		 * @return returns true if entity should be removed from collection
		 */
		boolean filterObstacle(Entity entity);
	}
	static class Filters
	{
		//allows anonymus classes to be initialized with parameter from
		//method slightly strange i know
		private static Rectangle rectangle; 
		public static EntityManager.ObstacleFilter allWithin(Rectangle rect)
		{
			rectangle = new Rectangle(rect);
			return new ObstacleFilter() {
				public boolean filterObstacle(Entity entity){
						if(!rectangle.intersects(entity.getBounds()))
							return true;
					return false;
				}
			};
		}
	}	
	
	
	
	

}
